<script lang="ts" setup>
import {onBeforeUnmount, onMounted, ref} from 'vue'
import http from '../utils/http.ts'
import AppServerForm from './AppServerForm.vue'
import {Delete, Edit, InfoFilled} from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus'
import router from '../router'
import MessageBox from '../components/MessageBox.vue'

// 列表
onMounted(() => {
  list()
})

const appServers = ref<AppServerListItem[]>([])

async function list() {
  const d = await http<PageResult<AppServerListItem>>({
    url: '/appServer/page',
  })
  appServers.value = d.records
}

// 新增
const appServerForm = ref<InstanceType<typeof AppServerForm>>()

function add() {
  appServerForm.value?.init()
}

// 修改
function edit(id: number) {
  appServerForm.value?.init(id)
}

// 删除
const selectedIds = ref<number[]>([])

// 删除单个
function delItem(id: number) {
  selectedIds.value = [id]
  deleteBatchBySelectedIds()
}
const handleSelectionChange = (appServerItem: AppServer[]) => {
  selectedIds.value = appServerItem.map(value => value.id)
}

// 批量删除已选择的记录
async function deleteBatchBySelectedIds() {
  await http({
    url: '/appServer',
    method: 'DELETE',
    data: selectedIds.value,
  })
  ElMessage({type: 'success', message: '删除成功'})
  await list()
}

// 启动/停止服务
async function startOrStop(row: AppServerListItem) {
  if (row.startOrStopButtonIsDisabled) return
  row.startOrStopButtonIsDisabled = true
  if (row.psInfo) {
    console.log('stop ', row.serverName)
    await http({
      url: `/appServer/stop/${row.id}`, method: 'POST',
    })
  } else {
    console.log('start ', row.serverName)
    await http({
      url: `/appServer/start/${row.id}`, method: 'POST',
    })
  }
  setTimeout(() => {
    row.startOrStopButtonIsDisabled = false
  }, 2000)
}

const serverStatusSocket = ref<WebSocket>()
const psInfos = ref()
onMounted(() => {
  // 建立WebSocket连接
  serverStatusSocket.value = new WebSocket('ws://127.0.0.1:10000/ws/serverStatus')
  // 监听WebSocket事件
  serverStatusSocket.value.addEventListener('open', () => {
    console.log('serverStatus 连接已建立')
  })
  serverStatusSocket.value.addEventListener('message', (event: any) => {
    psInfos.value = JSON.parse(event.data)
    for (let appServer of appServers.value) {
      appServer.psInfo = psInfos.value[appServer.hostIp];
    }
  })
  serverStatusSocket.value.addEventListener('close', () => {
    console.log('serverStatus 连接已关闭')
  })
})
onBeforeUnmount(() => {
  serverStatusSocket.value?.close()
})

const messageBox = ref<InstanceType<typeof MessageBox>>()
// 升级服务
function upgrade(id: number) {
  messageBox.value?.openMessageBox('upgrade', id)
}

function gotoUpgradeRecord(id: number) {
  router.push({
    path: '/upgradeRecord', query: {id: id},
  })
}
</script>

<template>
  <message-box ref="messageBox" @action-done="list"/>

  <div class="headerButtons">
    <el-button @click="add" type="primary" plain>新增</el-button>

    <el-popconfirm
        @confirm="deleteBatchBySelectedIds"
        placement="right"
        width="200"
        confirm-button-text="OK"
        cancel-button-text="No"
        :icon="InfoFilled"
        icon-color="#626AEF"
        title="确认删除选中的记录吗?"
    >
      <template #reference>
        <el-button type="danger" plain>删除选中</el-button>
      </template>
    </el-popconfirm>
  </div>

  <app-server-form ref="appServerForm" @saved="list"/>

  <el-table :data="appServers"
            @selection-change="handleSelectionChange"
            stripe style="width: 100%"
  >
    <el-table-column type="selection" width="55"/>

    <el-table-column prop="serverName" label="服务名称"/>
    <el-table-column prop="hostIp" label="主机ip"/>

    <el-table-column prop="serverLatestUpdateTime" label="服务最近更新时间"/>

    <el-table-column label="Operations">
      <template #default="scope">
        <el-button @click="upgrade(scope.row.id)" circle plain>
          <i class="iconfont icon-upgrade"></i>
        </el-button>
        <el-button @click="gotoUpgradeRecord(scope.row.id)" plain circle>
          <i class="iconfont icon-banbenhuitui"></i>
        </el-button>
      </template>
    </el-table-column>

    <el-table-column prop="psInfo.percentCpu" label="cpu%" width="70"/>
    <el-table-column prop="psInfo.residentSetSize" label="residentSetSize"/>
    <el-table-column prop="psInfo.latestStartTime" label="latestStartTime"/>

    <el-table-column prop="psInfo.elapsedTime" label="elapsedTime">
      <template #default="scope">
        <el-tag v-if="scope.row.psInfo" type="success" effect="plain" size="large" style="font-size: 18px">
          {{ scope.row.psInfo?.elapsedTime }}
        </el-tag>
      </template>
    </el-table-column>

    <el-table-column prop="psInfo.processId" label="processId" width="100"/>

    <el-table-column label="start/stop">
      <template #default="scope">
        <div @click="startOrStop(scope.row)">
          <el-button v-if="scope.row.psInfo" plain circle :disabled="scope.row.startOrStopButtonIsDisabled">
            <i class="iconfont icon-tingzhi"></i>
          </el-button>
          <el-button v-else plain circle :disabled="scope.row.startOrStopButtonIsDisabled">
            <i class="iconfont icon-qidong"></i>
          </el-button>
        </div>
      </template>
    </el-table-column>

    <el-table-column label="操作">
      <template #default="scope">
        <el-button @click="edit(scope.row.id)" :icon="Edit" type="primary" plain circle/>
        <el-popconfirm
            @confirm="delItem(scope.row.id)"
            placement="right"
            width="200"
            confirm-button-text="OK"
            cancel-button-text="No"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="确认删除这条记录吗?"
        >
          <template #reference>
            <el-button type="danger" :icon="Delete" circle plain/>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<style scoped lang="stylus">
$margin-size = 20px

.el-table {
  //font-size: 14px;
}

.headerButtons
  margin-bottom $margin-size
  display flex

  > *:nth-of-type(2)
    margin-left $margin-size
</style>
